//
//  HRAccessToken.swift
//  weiBo
//
//  Created by helong on 16/7/10.
//  Copyright © 2016年 helong. All rights reserved.
//

import UIKit
//  归档存储的路径定义成宏
let Path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userInfos.archive")

class HRAccessToken: NSObject,NSCoding {
    //授权码
    var access_token: String?
    //  授权的有效期,单位值秒  NSTimeInterval  是一个double类型的
    var expires_in: NSTimeInterval = 0{
        //当这个属性被赋值的时候会触发didSet这个方法
        didSet{
            //  授权有效期单位为妙转化成时间
            expiresTime = NSDate().dateByAddingTimeInterval(expires_in)
        }
    }
    //过期的日期
    var expiresTime: NSDate?
    //  用户id
    var uid: Int64 = 0
    //用户姓名
    var name: String?
    //用户头像
    var avatar_large: String?
  
    
 // MARK: - kvc赋值
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
// MARK: - 重写description方法
    override var description: String{
        let keys = ["access_token", "expires_in", "uid", "name", "avatar_large", "expiresTime"]
        return dictionaryWithValuesForKeys(keys).description
    }
    
// MARK: - 归档的协议方法
    //  将所有属性归档的方法
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeInt64(uid, forKey: "uid")
        aCoder.encodeObject(expiresTime, forKey: "expiresTime")
    }
    //  接档的方法
    required init?(coder aDecoder: NSCoder) {
        
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        uid = aDecoder.decodeInt64ForKey("uid")
        expiresTime = aDecoder.decodeObjectForKey("expiresTime") as? NSDate
        
    }
 // MARK: - 存储的方法
     func saveUserInfo() -> Bool{
        //存储对象
       let result = NSKeyedArchiver.archiveRootObject(self, toFile: Path)
        return result
    }
 // MARK: - 读取的方法
   class func readUserInfo() -> HRAccessToken?{
    
   return  NSKeyedUnarchiver.unarchiveObjectWithFile(Path) as? HRAccessToken
    
    }
}


